package com.becca.cake.service.couponRule.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.becca.cake.core.exception.ServiceException;
import com.becca.cake.dao.couponRule.CouponRuleDAO;
import com.becca.cake.dao.goods.GoodsDAO;
import com.becca.cake.dao.users.UserManagerDAO;
import com.becca.cake.model.coupon.GoodsPriceSizeRuleModel;
import com.becca.cake.model.coupon.PartookCouponRuleModel;
import com.becca.cake.model.coupon.RuleGroupModel;
import com.becca.cake.model.coupon.SalesRuleGroupModel;
import com.becca.cake.model.coupon.SalesRuleModel;
import com.becca.cake.model.goods.GoodsPriceSizeModel;
import com.becca.cake.model.goods.GoodsPriceSizeTreeModel;
import com.becca.cake.model.goods.GoodsTreeModel;
import com.becca.cake.model.users.UserCouponModel;
import com.becca.cake.model.users.UsersModel;
import com.becca.cake.service.couponRule.ICouponRuleService;
import com.becca.cake.util.DateUtils;

/**
 * 分享红包规则service实现类
 * @copyright  尊星(上海)信息科技有限公司
 * @author 
 * @date 2016年6月7日 下午5:05:59
 */
@Service
public class CouponRuleServiceImpl implements ICouponRuleService {

    @Autowired
    private CouponRuleDAO  couponRuleDAO;

    @Autowired
    private GoodsDAO       goodsDAO;

    @Autowired
    private UserManagerDAO userManagerDAO;

    @Override
    public List<PartookCouponRuleModel> selectCouponRule(Map<String, Object> map)
                                                                                 throws ServiceException {
        return this.couponRuleDAO.selectCouponRule(map);
    }

    @Override
    public Long selectCouponRuleCount(Map<String, Object> map) throws ServiceException {
        return this.couponRuleDAO.selectCouponRuleCount(map);
    }

    @Override
    public PartookCouponRuleModel selectCouponRuleById(Integer id) throws ServiceException {
        // 1.step 校验红包规则ID是否为空
        PartookCouponRuleModel.validSelectCouponRuleById(id);
        return this.couponRuleDAO.selectCouponRuleById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updateCouponRule(PartookCouponRuleModel partookCouponRuleModel, String trueName)
                                                                                                throws ServiceException {
        // 1.step 校验是否为空
        PartookCouponRuleModel.validCouponRuleIsNull(partookCouponRuleModel);
        partookCouponRuleModel.setUpdatedName(trueName);
        partookCouponRuleModel.setIsEnable(PartookCouponRuleModel.IS_ENALBE);
        this.couponRuleDAO.updateCouponRule(partookCouponRuleModel);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updCouponRuleIsEnable(Map<String, Object> map) throws ServiceException {
        Long isNotEnable = this.couponRuleDAO.isCouponRuleNotEnable(map);
        if (isNotEnable != 0) {
            throw new ServiceException(PartookCouponRuleModel.PARTOOK_COUPON_RULE_IS_DELETE);
        }
        this.couponRuleDAO.updCouponRuleIsEnable(map);
    }

    @Override
    public List<UserCouponModel> selectUserCoupon(Map<String, Object> map) throws ServiceException {
        return this.couponRuleDAO.selectUserCoupon(map);
    }

    @Override
    public Long selectUserCouponCount(Map<String, Object> map) throws ServiceException {
        return this.couponRuleDAO.selectUserCouponCount(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void insertUserCoupon(Map<String, Object> map) throws ServiceException {
        UserCouponModel userCouponModel = (UserCouponModel) map.get("userCouponModel");
        Integer isUseDate = Integer.valueOf(map.get("isUseDate").toString());
        // 1.step 校验
        UserCouponModel.validInsetUserCoupon(userCouponModel, isUseDate);
        userCouponModel.setCouponStatus(UserCouponModel.COUPON_STATUS_NO_USER);
        userCouponModel.setPartookCouponSource(UserCouponModel.COUPON_PARTTOOK_SOURCE);

        if (isUseDate == UserCouponModel.COUPON_USER_END_DATE) {
            if (map.get("useDate") != null) {
                Integer useDate = Integer.valueOf(map.get("useDate").toString());
                userCouponModel.setUserEndDate(DateUtils.getSomeDayDate(useDate));
            } else {
                throw new ServiceException(UserCouponModel.USE_DATE_NULL);
            }
        }
        this.couponRuleDAO.insertUserCoupon(userCouponModel);
    }

    @Override
    public List<RuleGroupModel> selectRuleGroup(Map<String, Object> map) throws ServiceException {
        return this.couponRuleDAO.selectRuleGroup(map);
    }

    @Override
    public Long selectRuleGroupCount(Map<String, Object> map) throws ServiceException {
        return this.couponRuleDAO.selectCouponRuleCount(map);
    }

    @Override
    public RuleGroupModel queryRuleGroupById(Integer id) throws ServiceException {
        // 1.step 校验规则组ID是否为空
        RuleGroupModel.validQueryRuleGroupById(id);
        return this.couponRuleDAO.queryRuleGroupById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void insertOrUpdateRuleGroup(RuleGroupModel ruleGroupModel, String trueName)
                                                                                       throws ServiceException {
        // 1.step 校验
        RuleGroupModel.validAddOrUpdRuleGroup(ruleGroupModel);
        if (ruleGroupModel.getId() == null) {
            ruleGroupModel.setCreatedName(trueName);
            this.couponRuleDAO.insertRuleGroup(ruleGroupModel);
        } else {
            this.couponRuleDAO.updRuleGroup(ruleGroupModel);
        }
    }

    @Override
    public List<SalesRuleModel> selectSalesRule(Map<String, Object> map) throws ServiceException {
        return this.couponRuleDAO.selectSalesRule(map);
    }

    @Override
    public Long selectSalesRuleCount(Map<String, Object> map) throws ServiceException {
        return this.couponRuleDAO.selectSalesRuleCount(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updSalesRuleGroup(Map<String, Object> map) throws ServiceException {
        String ruleGroupId = map.get("ruleGroupId").toString();
        this.couponRuleDAO.deleteSalesRuleGroup(ruleGroupId);
        this.couponRuleDAO.insertSalesRuleGroup(map);
    }

    @Override
    public List<SalesRuleGroupModel> querySalesRuleGroupById(Integer ruleGroupId)
                                                                                 throws ServiceException {
        return this.couponRuleDAO.querySalesRuleGroupById(ruleGroupId);
    }

    @Override
    public void insertOrUpdateSalesRule(SalesRuleModel salesRuleModel, String trueName)
                                                                                       throws ServiceException {
        SalesRuleModel.validSaveSalesRule(salesRuleModel);
        if (salesRuleModel.getId() == null) {
            salesRuleModel.setCreatedName(trueName);

            salesRuleModel.setIsEnable(SalesRuleModel.BYTE_IS_ENABLE_USER);
            this.couponRuleDAO.insertSalesRule(salesRuleModel);
        } else {
            salesRuleModel.setUpdatedName(trueName);
            this.couponRuleDAO.updSalesRule(salesRuleModel);
        }
    }

    @Override
    public SalesRuleModel querySalesRuleById(Integer id) throws ServiceException {
        // 1.step 校验规则ID是否为空
        SalesRuleModel.validSaveSalesRuleIdNull(id);
        return this.couponRuleDAO.querySalesRuleById(id);
    }

    @Override
    public void updIsEnableById(Map<String, Object> map) throws ServiceException {
        Integer id = Integer.valueOf(map.get("id").toString());
        // 1.step 校验规则ID是否为空
        SalesRuleModel.validSaveSalesRuleIdNull(id);
        Long isEnableExist = this.couponRuleDAO.isEnableExist(map);
        String isEnable = map.get("isEnable").toString();
        if (isEnableExist != 0) {
            if (SalesRuleModel.IS_ENABLE_USE.equals(isEnable)) {
                throw new ServiceException(SalesRuleModel.IS_ENABLE_EXIST);
            } else {
                throw new ServiceException(SalesRuleModel.IS_NOT_ENABLE_EXIST);
            }
        }
        this.couponRuleDAO.updIsEnableById(map);
    }

    @Override
    public List<GoodsTreeModel> selectGoodsTree(Integer goodsStatus, Integer isDelete)
                                                                                      throws ServiceException {
        List<GoodsTreeModel> goodsTreeList = this.goodsDAO.selectGoodsTree(goodsStatus);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        for (GoodsTreeModel goodsTreeModel : goodsTreeList) {
            paramMap.put("goodsId", goodsTreeModel.getId());
            paramMap.put("isDelete", isDelete);
            List<GoodsPriceSizeTreeModel> priceSizeTreeList = this.goodsDAO
                .selectGoodsPriceSizeTree(paramMap);
            goodsTreeModel.setChildren(priceSizeTreeList);
        }
        return goodsTreeList;

    }

    @Override
    public List<GoodsPriceSizeTreeModel> selectGoodsPriceSizeTree(Map<String, Object> map)
                                                                                          throws ServiceException {
        return this.goodsDAO.selectGoodsPriceSizeTree(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updateGoodsRule(Integer salesRuleId, String[] goodsPriceSizeIds)
                                                                                throws ServiceException {
        List<GoodsPriceSizeRuleModel> list = new ArrayList<GoodsPriceSizeRuleModel>();
        for (int i = 0; i < goodsPriceSizeIds.length; i++) {
            GoodsPriceSizeModel goodsPriceSizeModel = this.goodsDAO
                .selectGoodsPriceSizeModelById(Integer.valueOf(goodsPriceSizeIds[i]));
            GoodsPriceSizeRuleModel goodsPriceSizeRuleModel = new GoodsPriceSizeRuleModel();
            goodsPriceSizeRuleModel.setSalesRuleId(salesRuleId);
            goodsPriceSizeRuleModel.setGoodsPriceSizeId(goodsPriceSizeModel.getId());
            goodsPriceSizeRuleModel.setGoodsId(goodsPriceSizeModel.getGoodsId());
            list.add(goodsPriceSizeRuleModel);
        }
        // 1.step 先删除原先的商品规格
        this.couponRuleDAO.deleteGoodsPriceSizeFromRule(salesRuleId);
        // 2.step 添加商品规格
        this.couponRuleDAO.insertGoodsPriceSizeToRule(list);
    }

    @Override
    public List<GoodsPriceSizeRuleModel> selectGoodsBySalesRuleId(Integer salesRuleId)
                                                                                      throws ServiceException {
        return this.couponRuleDAO.selectGoodsBySalesRuleId(salesRuleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void insertAllUserCoupon(Map<String, Object> map) throws ServiceException {
        UserCouponModel userCouponModel = (UserCouponModel) map.get("userCouponModel");
        Integer isUseDate = Integer.valueOf(map.get("isUseDate").toString());
        // 1.step 校验
        UserCouponModel.validInsetAllUserCoupon(userCouponModel, isUseDate);
        userCouponModel.setCouponStatus(UserCouponModel.COUPON_STATUS_NO_USER);
        userCouponModel.setPartookCouponSource(UserCouponModel.COUPON_PARTTOOK_SOURCE);
        if (isUseDate == UserCouponModel.COUPON_USER_END_DATE) {
            if (map.get("useDate") != null) {
                Integer useDate = Integer.valueOf(map.get("useDate").toString());
                userCouponModel.setUserEndDate(DateUtils.getSomeDayDate(useDate));
            } else {
                throw new ServiceException(UserCouponModel.USE_DATE_NULL);
            }
        }
        //step2:查询全部可用用户信息
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userType", "0,1");
        paramMap.put("status", "0");
        List<UsersModel> listUsers = this.userManagerDAO.selectAllUsableUsers(paramMap);
        if (listUsers != null && listUsers.size() > 0) {
            for (UsersModel usersModel : listUsers) {
                userCouponModel.setUserMobileNo(usersModel.getMobileNo());
                this.couponRuleDAO.insertUserCoupon(userCouponModel);
            }
        }
    }
}
